# _*_ coding: utf-8 _*_
# @Author : zzg
# motto   : 有教无类，陪伴呵护

from flask import Flask, render_template, request, jsonify, flash, redirect, Response
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
from datetime import datetime
from flask_wtf import FlaskForm
from werkzeug.exceptions import abort
from wtforms import StringField,IntegerField
from wtforms.validators import Regexp,ValidationError,EqualTo,InputRequired,Length,Required,DataRequired
from flask_wtf import CSRFProtect

app = Flask(__name__)

manager = Manager(app)
# 设置连接数据
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:yzxa1234.@124.221.93.136:3308/flask'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

app.config['SECRET_KEY'] = 'adsasdasdzxcasfadsf'

db = SQLAlchemy(app)

CSRFProtect(app)

# 第一个参数是Flask的实例，第二个参数是Sqlalchemy数据库实例
Migrate(app, db)

# manager是Flask-Script的实例，这条语句在flask-Script中添加一个db命令
manager.add_command('db', MigrateCommand)


class Infos(db.Model):
    # __table_args__ = {'extend_existing': True}
    __tablename__ = 'db_infos'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), nullable=True)
    codecoll = db.Column(db.String(10), nullable=True)
    echnology = db.Column(db.String(200), nullable=True)
    direction = db.Column(db.String(200), nullable=True)
    price = db.Column(db.String(50), nullable=True)
    create_time = db.Column(db.DateTime, default=datetime.now)

    def __repr__(self):
        return "<Role %s>" % self.name


@app.route('/')
def index():
    """
    首页数据展示
    查询 + 未查询
    分页   前端：上（上一页） 中（展示的数字） 下（下一页）   上一页 1 ... 7 8 9 ... 20  下一页
    :return:
    """
    key = request.args.get('key',None)
    page = request.args.get('page',default=1,type=int)

    data = Infos.query.filter(Infos.name.like('%'+key+'%') | Infos.echnology.like('%'+key+'%')) if key else Infos.query
    pag = data.paginate(
        page=page,
        per_page=8,
    )
    persons = pag.items
    return render_template('admins.html',data = persons,pagination=pag)


class DataForm(FlaskForm):
    """
    验证前台传的数据必须符合这里面的要求
    """
    dh = StringField(validators=[DataRequired(message='请填写代号'),Length(1, 50,message='须在1～50个字符之间')])
    ml = StringField(validators=[DataRequired(message='请填写马岭'),Length(1, 3,message='须在1～3个字符之间')])
    yy = StringField(validators=[DataRequired(message='请填写语言'),Length(1, 50,message='须在1～50个字符之间')])
    fx = StringField(validators=[DataRequired(message='请填写方向'),Length(1, 50,message='须在1～50个字符之间')])
    xz = StringField(validators=[DataRequired(message='请填写薪资'),Length(1, 50,message='须在1～50个字符之间')])


def save_data(obj,edit=False,delete=False):
    try:
        if edit:
            db.session.merge(obj)
        elif delete:
            db.session.delete(obj)
        else:
            db.session.add(obj)
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()


@app.route('/add',methods=['GET','POST'])
def add_data():
    if request.method.lower() == 'post':
        form = DataForm(request.form)
        if form.validate():
            info = Infos()
            info.name = form.dh.data
            info.codecoll = form.ml.data
            info.echnology = form.yy.data
            info.direction = form.fx.data
            info.price = form.xz.data
            save_data(info)  # 保存数据
            flash('数据添加成功')
            return redirect('/')
        else:
            return jsonify({'message':form.errors})
    return render_template('add_edit.html')


@app.route('/edit/<id>',methods=['GET','POST'])
def edit_data(id):
    title = '数据修改'
    data = Infos.query.filter_by(id=id).first()
    if request.method.lower() == 'post':
        if data:
            form = DataForm(request.form)
            if form.validate():
                data.name = form.dh.data
                data.codecoll = form.ml.data
                data.echnology = form.yy.data
                data.direction = form.fx.data
                data.price = form.xz.data
                # 保存数据
                save_data(obj=data,edit=True)
                flash('数据添加成功')
                return redirect('/')
            else:
                return jsonify({'message':form.errors})
        else:
            abort(Response('参数错误'))
    return render_template('add_edit.html',data=data,title=title)


@app.route('/del/<id>',methods=['GET','POST'])
def del_data(id):
    data = Infos.query.filter_by(id=id).first()
    if data:
        save_data(obj=data,delete=True)
        return redirect('/')
    else:
        abort(Response('参数错误'))


if __name__ == '__main__':
    manager.run()
